package com.share.device.emqx;

import com.share.common.core.exception.ServiceException;
import com.share.device.emqx.callback.OnMessageCallback;
import com.share.device.emqx.config.EmqxProperties;
import com.share.device.emqx.constant.EmqxConstants;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.stereotype.Component;

/**
 * EMQX客户端包装器：封装mqtt连接、订阅与发布接口
 * @author zxl
 * @date 2025年03月28日 21:47
 */
@Slf4j
@Component
public class EmqxClientWrapper {
    @Resource
    private EmqxProperties emqxProperties;

    private MqttClient client;

    @Resource
    private OnMessageCallback onMessageCallback;

    /**
     * 初始化mqtt客户端
     */
    @PostConstruct
    private void init() {
        // 创建一个内存持久化对象mqttClientPersistence，用于存储MQTT客户端的会话状态和消息
        // 1.使用MemoryPersistence类实现内存中的数据持久化
        // 2.该对象将在后续MQTT客户端初化时使用，确保会话数据不会丢失
        MqttClientPersistence mqttClientPersistence = new MemoryPersistence();

        try {
            // 新建客户端 参数：MQTT服务器的地址、客户端ID、持久化对象
            client = new MqttClient(
                    emqxProperties.getServerURI(),
                    emqxProperties.getClientId(),
                    mqttClientPersistence);
            //设置回调
            client.setCallback(onMessageCallback);
            // 建立连接
            connect();
        } catch (MqttException e) {
            log.error("MqttClient创建失败");
            throw new ServiceException(e.getMessage());
        }
    }

    public Boolean connect() {
        try {
            // 设置连接的配置
            client.connect(mqttConnectOptions());
            log.info("连接成功");
            // 订阅
            String[] topics = {
                    EmqxConstants.TOPIC_POWERBANK_CONNECTED,
            EmqxConstants.TOPIC_POWERBANK_UNLOCK,
            EmqxConstants.TOPIC_PROPERTY_POST
            };
            client.subscribe(topics);
            return true;
        } catch (MqttException e) {
            log.error("连接失败");
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 创建MQTT配置类
     * @return
     */
    private MqttConnectOptions mqttConnectOptions() {
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setUserName(emqxProperties.getUsername());
        mqttConnectOptions.setPassword(emqxProperties.getPassword().toCharArray());
        // 是否自动重新连接
        mqttConnectOptions.setAutomaticReconnect(true);
        // 是否清除之前的连接信息
        mqttConnectOptions.setCleanSession(true);
        // 连接超时时间
        mqttConnectOptions.setConnectionTimeout(emqxProperties.getConnectionTimeout());
        // 心跳
        mqttConnectOptions.setKeepAliveInterval(emqxProperties.getKeepAliveInterval());
        return mqttConnectOptions;
    }

    /**
     * 发布消息
     * @param topic 主题
     * @param data 数据
     */
    public void publish(String topic, String data) {
        try {
            MqttMessage message = new MqttMessage(data.getBytes());
            message.setQos(2);
            client.publish(topic, message);
        } catch (MqttException e) {
            log.error("消息发布失败");
            e.printStackTrace();
        }
    }
}
